import json

from django_redis import get_redis_connection

consumer_object_list = []


def get_redis_order_key(side, symbol):
    return 'lo-{}-{}'.format(side, symbol)


def get_market_orders(jo):
    goods_symbol = jo['symbol']
    size = jo['size']
    buy_order_key = get_redis_order_key(1, goods_symbol)
    sell_order_key = get_redis_order_key(2, goods_symbol)
    conn = get_redis_connection(alias='ex-engine')
    buy_orders = conn.lrange(buy_order_key, 0, size)
    sell_orders = conn.lrange(sell_order_key, 0, size)
    buy_order_arr = []
    sell_order_arr = []
    for val in buy_orders:
        buy_order_arr.append(json.loads(str(val, 'utf-8')))
    for val in sell_orders:
        sell_order_arr.append(json.loads(str(val, 'utf-8')))
    return buy_order_arr, sell_order_arr


class ParseSocketMessage:
    typ = ''
    data = None

    def __init__(self, message):
        data = message.get('text')
        if data is not None:
            try:
                jo = json.loads(data)
                self.typ = jo['type']
                self.data = jo['data']
            except Exception as ex:
                print(ex)
